<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="s" uri="http://www.springframework.org/tags" %>
<!DOCTYPE html>
<html>
<head>
<jsp:include page="/WEB-INF/views/head.jsp"/>
<style>
body{overflow-x:auto;}
.ztree li span.button.switch.level0 {visibility:hidden; width:1px;}
.ztree li ul.level0 {padding:0; background:none;}
</style>
<script>
function dblClickExpand(treeId, treeNode) {
	return treeNode.level > 0;
}

var curExpandNode = null;
function onExpand(event, treeId, treeNode) {
	var openIds =  $.cookie('open_ids');
	openIds = openIds ? openIds : ",";
	if(openIds.indexOf(","+treeNode.id+",")==-1) {
		openIds += treeNode.id + ",";
		$.cookie('open_ids',openIds);
	}
  curExpandNode = treeNode;
}
function onCollapse(event, treeId, treeNode) {
	var openIds =  $.cookie('open_ids');
	var id = "," + treeNode.id + ",";
	if(openIds) {
		openIds = openIds.replace(id,",");
		$.cookie('open_ids',openIds);
	}
}
function isOpen(id) {
	var openIds =  $.cookie('open_ids');
	if(openIds) {
		return openIds.indexOf(","+id+",")!=-1;
	} else {
		return false;
	}
}
function beforeExpand(treeId, treeNode) {
  var pNode = curExpandNode ? curExpandNode.getParentNode():null;
  var treeNodeP = treeNode.parentTId ? treeNode.getParentNode():null;
  var zTree = $.fn.zTree.getZTreeObj("tree");
  for(var i=0, l=!treeNodeP ? 0:treeNodeP.children.length; i<l; i++ ) {
    if (treeNode !== treeNodeP.children[i]) {
      zTree.expandNode(treeNodeP.children[i], false);
    }
  }
  while (pNode) {
    if (pNode === treeNode) {
      break;
    }
    pNode = pNode.getParentNode();
  }
  if (!pNode) {
    singlePath(treeNode);
  }

}
function singlePath(newNode) {
  if (newNode === curExpandNode) return;

  var zTree = $.fn.zTree.getZTreeObj("tree"),
      rootNodes, tmpRoot, tmpTId, i, j, n;

  if (!curExpandNode) {
    tmpRoot = newNode;
    while (tmpRoot) {
      tmpTId = tmpRoot.tId;
      tmpRoot = tmpRoot.getParentNode();
    }
    rootNodes = zTree.getNodes();
    for (i=0, j=rootNodes.length; i<j; i++) {
      n = rootNodes[i];
      if (n.tId != tmpTId) {
        zTree.expandNode(n, false);
      }
    }
  } else if (curExpandNode && curExpandNode.open) {
    if (newNode.parentTId === curExpandNode.parentTId) {
      zTree.expandNode(curExpandNode, false);
    } else {
      var newParents = [];
      while (newNode) {
        newNode = newNode.getParentNode();
        if (newNode === curExpandNode) {
          newParents = null;
          break;
        } else if (newNode) {
          newParents.push(newNode);
        }
      }
      if (newParents!=null) {
        var oldNode = curExpandNode;
        var oldParents = [];
        while (oldNode) {
          oldNode = oldNode.getParentNode();
          if (oldNode) {
            oldParents.push(oldNode);
          }
        }
        if (newParents.length>0) {
          zTree.expandNode(oldParents[Math.abs(oldParents.length-newParents.length)-1], false);
        } else {
          zTree.expandNode(oldParents[oldParents.length-1], false);
        }
      }
    }
  }
  curExpandNode = newNode;
}
var setting = {
	view: {
		nameIsHTML: true,
	    showTitle: false,
		expandSpeed: "",
		dblClickExpand: dblClickExpand
	},
	callback: {
        beforeExpand: beforeExpand,
        onExpand: onExpand,
        onClick: onClick,
		onCollapse: onCollapse
	},
	data: {
		simpleData: {
			enable: true
		}
	}
};
var zNodes =[
	<c:forEach var="node" items="${nodeList}" varStatus="status">
		{
		    "id":${node.id},
            "pId":<c:out value="${node.parent.id}" default="null"/>,
            "name":"<c:out value='${node.name}'/>",
            <%--"name":"<c:out value='${node.name}'/> <span style='color:#c8103d;'><c:if test='${!empty node.infoModel}'>,${node.infoModel.name}</c:if></span>",--%>
            "position":${status.index},
            <c:choose><c:when test="${empty node.parent}">"open":true</c:when><c:otherwise>"open":isOpen(${node.id})</c:otherwise></c:choose>
		}<c:if test="${!status.last}">,</c:if>
	</c:forEach>
];

function fireClick(){
	var treeObj = $.fn.zTree.getZTreeObj("tree");
	var treeNodeArr = treeObj.getSelectedNodes();
	if(treeNodeArr.length>0) {
		onClick(null,"tree",treeNodeArr[0],null);
	}
}
$(function(){
    $("#showList").click(function() {
        $.cookie('show_list',this.checked);
        fireClick();
    });
    $("#showDescendants").click(function() {
        $.cookie('show_descendants',this.checked);
        fireClick();
    });
    var treeObj = $.fn.zTree.init($("#tree"), setting, zNodes);
    <c:choose>
    <c:when test="${empty param.noSelect}">
    $("#showList").prop("checked",$.cookie('show_list')!='false');
    $("#showDescendants").prop("checked",$.cookie('show_descendants')!='false');
    var selectId = $.cookie('select_id');
    if(selectId) {
        var nodeObj = treeObj.getNodeByParam("id",selectId);
        if(nodeObj) {
            treeObj.selectNode(nodeObj);
        }
    }
    </c:when>
    <c:otherwise>
    var nodes = treeObj.getNodes();
    if(nodes.length>0) {
        var nodeObj = nodes[0];
        treeObj.selectNode(nodeObj);
        $.cookie('select_id',nodeObj.id);
    } else {
        $.cookie('select_id',null);
    }
    </c:otherwise>
    </c:choose>

    <%--根据zNodes生成菜单--%>
    resetData();
//    默认点击第一个子选项
//    $("#menu a:first").trigger("click");

});
function resetData() {
    var zTree = $.fn.zTree.getZTreeObj("tree"),
        nodes = zTree.getNodes(), html = '<h3 class="menu-title">' + nodes[0].name + '</h3>';
    html += recursion(nodes[0].children, "root", "menu");
    $("body").append(html || "");

    $("#menu a").click(function() {
        var tar = $(this),
            parent = tar.parent(),
            next = tar.next(), ul_len = next.children().length,
            height = 0, isActive = parent.hasClass("active"), isOpen = parent.hasClass("open");
        if (ul_len > 0){
            let liH = next.children().height();
            if (isActive && isOpen){
                parent.removeClass("open");
                next.css("height", height).find("li").removeClass("active");
            }else if(isActive && !isOpen){
                parent.addClass("open");
                next.css("height", ul_len * liH + "px");
            }else {
                parent.addClass("active open").siblings().removeClass("active open").find("li").removeClass("active")
                    .end().children("ul").css("height", height);
                next.css("height", ul_len * liH + "px");
//                二级菜单默认点击第一个选项
//                if (!next.children().hasClass("active")){
//                    next.find("a").eq(0).trigger("click");
//                }
            }
        }else {
            parent.addClass("active").siblings().removeClass("active").find("li").removeClass("active")
                .end().children("ul").css("height", height);
        }
        onClick(null,"tree",zTree.getNodeByParam("id", $(this).parent().data("id")),null);
    });
}
function recursion(obj, type, id) {
    if (type === "root"){
        var menu = '<ul id="' + id + '" class="custom-menu menu-root">';
    }else {
        var menu = '<ul class="custom-menu">';
    }
    $.each(obj, function (idx, val) {
        var children = val.children;
        if (children && children.length > 0){
            menu += '<li data-id="' + val.id + '">' +
                '<a href="javascript:;">' +
                val.name +
                '<span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span>' +
                '</a>';
            menu += recursion(children);
        }else {
            menu += '<li data-id="' + val.id + '">' +
            '<a href="javascript:;">' +
            val.name +
            '</a>';
        }
        menu += '</li>';
    })
    menu += '</ul>';
    return menu;
}
function onClick(event, treeId, treeNode, clickFlag) {
//    取消父节点点击事件
//    if (treeNode.children !== undefined){
//        return;
//    }
    $.cookie('select_id',treeNode.id);
    if($("#showList").prop("checked")) {
//    if(treeNode.id!=null && treeNode.id!="" ){
//      if(!treeNode.children || treeNode.children.length<=0){
//        parent.frames["center"].location.href="forward.do?queryNodeId="+treeNode.id+"&showDescendants="+$("#showDescendants").prop("checked");
//      }else{
//        parent.frames["center"].location="about:blank";
//      }
//    }else{
//      parent.frames["center"].location="about:blank";
//    }
//        if(treeNode.nodeModel.flag){
//
//        }

        parent.frames["center"].location.href="forward.do?isCreate=${isCreate}&queryNodeId="+treeNode.id+"&showDescendants="+$("#showDescendants").prop("checked");

    }
}
</script>
</head>
<body class="skin-blue content-body">
<div style="padding:16px 0 2px 12px;font-size:16px;">
  <label class="checkbox-inline" style="display: none"><input id="showList" type="checkbox" checked/><s:message code="node.showList"/></label>
  <label class="checkbox-inline" style="display: none"><input id="showDescendants" type="checkbox" checked/><s:message code="node.showDescendants"/></label>
  <%-- <input type="button" value="<s:message code="refresh"/>" onclick="javascript:location.href=location.href"/> &nbsp; --%>
  <%-- <a href="javascript:location.href=location.href" class="ls-opt"><s:message code="refresh"/></a> &nbsp; --%>
  <%-- <a href="../model/list.do" target="center" class="ls-opt"><s:message code="model.management"/></a> &nbsp; --%>
</div>
<ul id="tree" class="ztree" style="margin:7px 0 0 7px;display: none;"></ul>
</body>
</html>